package com.example.state.order;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.statemachine.StateMachine;
import org.springframework.statemachine.persist.StateMachinePersister;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 *
 */
@Service("orderService")
public class OrderServiceImpl implements IOrderService {

    @Autowired
    private StateMachine<OrderStates, OrderStatesChangeEvent> stateMachine;

    // 持久化状态机状态
    @Autowired
    private StateMachinePersister<OrderStates, OrderStatesChangeEvent, Order> persist;

    private int id = 1;
    // 创建的订单暂时缓存起来，直到終态的订单再移除，享元模式
    private Map<Integer, Order> orders = new HashMap<>();

    @Override
    public Order create() {
        Order order = new Order();
        order.setStates(OrderStates.WAIT_PAYMENT);
        order.setId(id++);
        orders.put(order.getId(), order);
        return order;
    }

    @Override
    public Order pay(int id) {
        Order order = orders.get(id);
        System.out.println("线程名称：" + Thread.currentThread().getName() + " 尝试支付，订单号：" + id);
        Message message = MessageBuilder.withPayload(OrderStatesChangeEvent.PAYED)
                .setHeader("order", order).build();
        if (sendEvent(message, order)) {
            System.out.println("线程名称：" + Thread.currentThread().getName() + " 支付失败, 状态异常，订单号：" + id);
        }
        return order;
    }

    @Override
    public Order deliver(int id) {
        Order order = orders.get(id);
        System.out.println("线程名称：" + Thread.currentThread().getName() + " 尝试发货，订单号：" + id);
        if (!sendEvent(MessageBuilder.withPayload(OrderStatesChangeEvent.DELIVERY).setHeader("order", order).build(), orders.get(id))) {
            System.out.println("线程名称：" + Thread.currentThread().getName() + " 发货失败，状态异常，订单号：" + id);
        }
        return order;
    }

    @Override
    public Order receive(int id) {
        Order order = orders.get(id);
        System.out.println("线程名称：" + Thread.currentThread().getName() + " 尝试收货，订单号：" + id);
        if (!sendEvent(MessageBuilder.withPayload(OrderStatesChangeEvent.DELIVERY).setHeader("order", order).build(), orders.get(id))) {
            System.out.println("线程名称：" + Thread.currentThread().getName() + " 尝试收货，状态异常，订单号：" + id);
        }
        return order;
    }

    @Override
    public Map<Integer, Order> getOrders() {
        return orders;
    }

    private synchronized boolean sendEvent(Message<OrderStatesChangeEvent> message, Order order) {
        boolean result = false;
        try {
            // 状态机启动
            stateMachine.start();
            // 尝试恢复状态机状态
            persist.restore(stateMachine, order);
            // 添加延迟用于线程安全测试
            TimeUnit.SECONDS.sleep(1);
            // 将订单动作的事件发送给状态机
            result = stateMachine.sendEvent(message);
            // 持久化状态机状态
            persist.persist(stateMachine, order);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            stateMachine.stop();
        }
        return result;
    }
}
